﻿using JWT;
using JWT.Algorithms;
using JWT.Serializers;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace HCommon
{
    public static class EncryHelper
    {
        /// <summary>
        /// SHA256加密
        /// </summary>
        /// <param name="strData"></param>
        /// <returns></returns>
        public static string SHA256(string strData)
        {
            byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(strData);
            SHA256 sha256 = new SHA256CryptoServiceProvider();
            byte[] retVal = sha256.ComputeHash(bytValue);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < retVal.Length; i++)
            {
                sb.Append(retVal[i].ToString("x2"));
            }
            return sb.ToString();
        }


        /// <summary>
        /// Jwt加密
        /// </summary>
        /// <param name="secret"></param>
        /// <param name="payload"></param>
        /// <returns></returns>
        public static string JWT(string secret, JObject payload)
        {
            IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
            IJsonSerializer serializer = new JsonNetSerializer();
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
            var token = encoder.Encode(payload, secret);
            return token;
        }

        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="input">用户输入的内容</param>
        /// <returns>MD5加密后的字符串</returns>
        public static string Md5(string input)
        {
            MD5 md5 = MD5.Create();

            byte[] bytes = Encoding.Default.GetBytes(input);

            byte[] bytesMd5 = md5.ComputeHash(bytes);

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < bytesMd5.Length; i++)
            {
                sb.Append(bytesMd5[i].ToString("x2")); //32位小写
            }
            return sb.ToString();
        }
   }
}
